#include "app_player.h"
#include "ui_app_player.h"
#include <QDebug>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <string.h>
#include <fcntl.h>                          // 提供open()函数
#include <sys/types.h>                      // 提供mode_t类型
#include <sys/stat.h>                       // 提供open()函数的符号

extern int kbdfd,ledsfd,beepfd,adcfd;

app_player::app_player(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::app_player)
{
    ui->setupUi(this);
    Init();
}

app_player::~app_player()
{
    delete ui;
}

void app_player::Init()
{

    this->setWindowState(Qt::WindowNoState);

    Last_key_value = 0;
    lal = new myLabel(this);
    lal->setMinimumSize(QSize(0, 320));
    lal->setStyleSheet(QStringLiteral("background-color: rgb(0, 0, 0);"));
    ui->gridLayout->addWidget(lal, 0, 0, 1, 2);

    connect(lal,SIGNAL(SignalSendPlayPath(const QString)),
            this,SLOT(doProcessDragPlay(const QString)));

    playList.clear();
    play_index=0;
    isPlaying = -1;
    isSilence = false;
    isfull = false;

    playProces = new QProcess(this);
    connect(playProces,SIGNAL(readyRead()),
            this,SLOT(doProcessreadyRead()));
    myTimer = new QTimer(this);
    connect(myTimer,SIGNAL(timeout()),
            this,SLOT(doProcessTimeOut()));
    ui->voice_Slider->setValue(50);

    connect(lal,SIGNAL(SignalSendfullwin(bool)),
            this,SLOT(doProcessFullwin(bool)));


    KbdScanTimer = new QTimer(this);//创建一个定时器
    connect(KbdScanTimer, SIGNAL(timeout()), this, SLOT(deal_key()));//链接按键扫描定时器信号给KbdLedScan函数

    if(kbdfd>0)
    {
        KbdScanTimer->start(100);//开启100ms的按键和LED状态扫描
    }


}

void app_player::playMovie(const QString filename)
{

    QString program = "/usr/bin/mplayer";
    QStringList arguments;
    arguments<<filename;
    arguments<<"-wid"; //mplayer 将窗口指定到一个地方播放
    arguments<<QString::number(lal->winId());
//    arguments<<"-fs";  //让mplayer变为全屏模式
    arguments<<"-slave";  //让mplayer变为从模式
    arguments<<"-quiet";  //让mplayer变为静默模式
    //先关闭上一次的播放
    playProces->close();
    playProces->setProcessChannelMode(QProcess::MergedChannels);
    playProces->start(program,arguments);
    //qDebug()<<playList;
    isPlaying = 1;
    myTimer->start(1000);
    ui->play_Button->setStyleSheet("border-image: url(:/images/stop.png);");
    ui->seek_Slider->setValue(0);
}


void app_player::doProcessTimeOut()  //获取进度条
{
    if(isPlaying == 1)
    {
        QString cmd = QString("get_percent_pos\n");
        playProces->write(cmd.toLatin1()); //获取进度条
    }
}

void app_player::doProcessreadyRead()
{
    QString str = QString(playProces->readAll());
    if(str.contains("ANS_PERCENT_POSITION"))
    {
        str.replace("\n","");
        QString var = str.split("=").at(1);ui->seek_Slider->setValue(var.toUInt());
        var += "%";
        ui->percent_label->setText(var);

        if(var == "100")
        {  isPlaying = 2;
            ui->seek_Slider->setValue(100);
            ui->percent_label->setText("100%");
        }
    }
}


void app_player::doProcessDragPlay(const QString filename)
{
    if(playList.indexOf(filename)==-1)
    {
        playList << filename;
        play_index=playList.indexOf(filename);
    }
    else
        play_index = playList.indexOf(filename);

    isPlaying = 1;
    playMovie(playList.at(play_index));
}


void app_player::doProcessFullwin(bool ret)
{
    isfull = ret;
    if(ret)
    {
        /*this->showFullScreen();
        ui->seek_Slider->hide();
        ui->frame->hide();
        ui->percent_label->hide();*/
    }
    else
    {
        /*this->showNormal();
        ui->seek_Slider->show();
        ui->frame->show();
        ui->percent_label->show();*/
    }
    playProces->close();
    KbdScanTimer->stop();
    this->parentWidget()->show();
    this->close();
//    this->show();

}



void app_player::on_play_Button_clicked()
{
    if(isPlaying == -1)
    {
        return;
    }
    QString iconName;
    QString cmd = "pause\n";  //指令传递给进程进行暂停 或 播放
    if(isPlaying == 1) //在播放  需要暂停
    {
        isPlaying = 2;
        ui->play_Button->setStyleSheet("border-image: url(:/images/playing.png);");
    }
    else if(isPlaying == 2)  //在暂停  需要播放
    {
        isPlaying = 1;
        ui->play_Button->setStyleSheet("border-image: url(:/images/stop.png);");
    }

    playProces->write(cmd.toLatin1()); //写入暂停或者播放指令
}



void app_player::on_open_file_Button_clicked()
{
//    QString cmd = "pause\n";  //指令传递给进程进行暂停 或 播放
//    if(isPlaying == 1) //在播放  需要暂停
//    {
//        isPlaying = 2;
//        ui->play_Button->setStyleSheet("border-image: url(:/images/playing.png);");
//    }
//     playProces->write(cmd.toLatin1()); //写入暂停或者播放指令
//     this->resize(this->size());

    QStringList array = QFileDialog::getOpenFileNames(this,"需要播放的文件",
                                  "/root","video(*.mp4 *.avi *.rmvb *.mkv)");
//        this->resize(this->size());
    //qDebug()<<array;
    if(array.length()<=0)
    {
        return;
    }
    for(int i=0; i< array.length(); i++)
    {
        if(playList.indexOf(array[i])==-1)
        {
            playList << array[i];
            play_index=playList.length()-1;
        }
        else
            play_index = playList.indexOf(array[i]);
    }

    qDebug()<<playList;

    playMovie(playList.at(play_index));
}

void app_player::on_Button_previou_clicked()
{
    qDebug()<<playList.length() ;
    if(playList.length() == 0)
        return;
    if(play_index == 0)
    {
        play_index = playList.length()-1;
        playMovie(playList.at(play_index));
    }
    else if(play_index >0)
    {play_index--;
    playMovie(playList.at(play_index));}
}

void app_player::on_next_Button_clicked()
{
    if(playList.length() == 0)
        return;
    if(play_index == playList.length()-1)
    {
        play_index = 0;
        playMovie(playList.at(play_index));
    }
    else if(play_index<playList.length()-1)
    {play_index++;
    playMovie(playList.at(play_index));}
}


void app_player::on_seek_Slider_valueChanged(int value)
{


}

void app_player::on_voice_Slider_valueChanged(int value)
{
    //qDebug()<<"value="<<value;
    if(isPlaying == 1 || isPlaying == 2)
    {
        QString cmd = QString("volume %1 1\n").arg(value);
        playProces->write(cmd.toLatin1());  //修改音量大小
        if(isPlaying == 2)
        {QString cmd = "pause\n";
        playProces->write(cmd.toLatin1());  //进行暂停
        }
    }
}


void app_player::on_set_silence_Button_clicked()
{
    QString iconName;
    if(isSilence == false)
    {
        QString cmd = QString("volume 0 1\n");
        playProces->write(cmd.toLatin1());  //修改音量大小
        if(isPlaying == 2)
        {
            QString cmd = "pause\n";
            playProces->write(cmd.toLatin1());  //进行暂停
        }
        isSilence = true;
        iconName = ":/images/silence.png";
    }
    else if(isSilence == true)
    {
        int value = ui->voice_Slider->value();
        on_voice_Slider_valueChanged(value);
        isSilence = false;
        iconName = ":/images/voice.png";
    }
    //ui->set_silence_Button->setIcon(QIcon(iconName));
}

void app_player::deal_key()
{
    if(!(kbdfd<0))//按键驱动可用，读取按键状态
    {
        read(kbdfd,&KbdStatus,1);
        if(Last_key_value == KbdStatus)  //按一下触发一次
        {
            return;
        }

        switch (KbdStatus)
        {
        case 1:   //第一个按键  //按键1控制的关闭限位
            {
            qDebug()<<"on_open_file_Button_clicked";
            Last_key_value = 1;
            on_open_file_Button_clicked();
            break;}
        case 2:   //第二个按键  //按键2控制的打开限位
            {
            qDebug()<<"on_play_Button_clicked";
            Last_key_value = 2;
            on_play_Button_clicked();
            break;}
        case 4:   //第三个按键  //按键3控制的关闭过载
            {
            qDebug()<<"on_Button_previou_clicked";
            Last_key_value = 4;
            on_Button_previou_clicked();
            break;
            }
        case 8:  //第四个按键  //按键4控制的打开过载
        {
            qDebug()<<"on_next_Button_clicked";
            Last_key_value = 8;
            on_next_Button_clicked();
            break;
        default:
                Last_key_value = 0;
                break;}
        }
    }
}

void app_player::on_pushButton_clicked()
{
    playProces->close();
    KbdScanTimer->stop();
    this->parentWidget()->show();
    this->close();
}

void app_player::on_seek_Slider_sliderReleased()
{
//    int value = ui->seek_Slider->value();
//    if(isPlaying == 1 || isPlaying == 2)
//    {
//        QString cmd = QString("seek %1 1\n").arg(value);
//        playProces->write(cmd.toLatin1());  //跳转进度
//        if(isPlaying == 2)
//        {QString cmd = "pause\n";
//        playProces->write(cmd.toLatin1());  //进行暂停
//        }
//    }
}

void app_player::on_seek_Slider_rangeChanged(int min, int max)
{

}

void app_player::on_seek_Slider_sliderMoved(int position)
{
        int value = ui->seek_Slider->value();
        if(isPlaying == 1 || isPlaying == 2)
        {
            QString cmd = QString("seek %1 1\n").arg(position);
            playProces->write(cmd.toLatin1());  //跳转进度
            if(isPlaying == 2)
            {QString cmd = "pause\n";
            playProces->write(cmd.toLatin1());  //进行暂停
            }
        }
}

void app_player::on_seek_Slider_sliderPressed()
{

}
